<template>
  <div class="meal-record-page">
    <div class="page-container">
      <div class="header">
        <h2 class="page-title">膳食记录</h2>
        <el-button 
          type="primary" 
          :icon="Plus"
          @click="showAddFoodDialog = true"
        >
          添加食物记录
        </el-button>
      </div>

      <div class="sub-header">
        <date-selector
          v-model="selectedDate"
          @change="handleDateChange"
        />
        <div class="nutrition-summary" v-if="mealRecords?.length">
          <span>今日摄入：</span>
          <el-tag size="small" type="info">热量 {{ totalNutrition.calories }}kcal</el-tag>
          <el-tag size="small" type="success">蛋白质 {{ totalNutrition.protein }}g</el-tag>
          <el-tag size="small" type="warning">碳水 {{ totalNutrition.carbohydrates }}g</el-tag>
          <el-tag size="small" type="danger">脂肪 {{ totalNutrition.fat }}g</el-tag>
        </div>
      </div>
    </div>

    <div class="content-container">
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>

      <template v-else>
        <div v-if="mealRecords?.length > 0">
          <meal-card
            v-for="record in mealRecords"
            :key="record.recordId"
            :record="record"
            :loading="loading"
            @add-food="handleAddFood"
            @edit="handleEdit"
            @delete="handleDelete"
          />
        </div>

        <el-empty
          v-else
          class="empty-state"
          description="暂无膳食记录"
        >
        </el-empty>
      </template>
    </div>

    <add-food-dialog
      v-model:visible="showAddFoodDialog"
      @confirm="handleAddFood"
    />
    
    <edit-food-dialog
      v-model:visible="showEditDialog"
      :record="editingRecord"
      @confirm="handleEditConfirm"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import DateSelector from '@/components/meal-record/DateSelector.vue'
import MealCard from '@/components/meal-record/MealCard.vue'
import AddFoodDialog from '@/components/meal-record/AddFoodDialog.vue'
import EditFoodDialog from '@/components/meal-record/EditFoodDialog.vue'
import { useRouter } from 'vue-router'
import request from '@/config/axios'

const store = useStore()
const router = useRouter()
const today = new Date().toISOString().split('T')[0]
const selectedDate = ref(today)
const token = ref(null)

const userInfo = computed(() => store.state.user.userInfo)
const userId = computed(() => userInfo.value?.userId)

const mealRecords = computed(() => {
  const records = store.getters['meals/getMealRecords']
  console.log('Computed mealRecords:', records)
  if (!Array.isArray(records)) {
    console.warn('getMealRecords returned non-array:', records)
    return []
  }
  return records
})
const loading = computed(() => store.getters['meals/isLoading'])

onMounted(async () => {
  token.value = localStorage.getItem('token')
  if (!token.value || !userId.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  await fetchDailyRecords()
})

const fetchDailyRecords = async () => {
  if (!userId.value) {
    ElNotification({
      title: '提示',
      message: '未获取到用户信息，请重新登录',
      type: 'warning'
    })
    router.push('/login')
    return
  }

  if (!token.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  const formattedDate = selectedDate.value
  console.log('请求日期:', formattedDate)

  try {
    console.log('开始获取膳食记录:', { date: formattedDate, userId: userId.value })
    await store.dispatch('meals/fetchDailyMeals', {
      date: formattedDate,
      userId: userId.value
    })
    const error = store.getters['meals/getError']
    if (error) {
      ElMessage.error(error)
      return
    }
    console.log('获取膳食记录成功')
  } catch (error) {
    console.error('获取膳食记录失败:', error)
    ElMessage.error('获取膳食记录失败')
  }
}

const handleDateChange = (date) => {
  selectedDate.value = date
  fetchDailyRecords()
}

const handleAddFood = async (detail) => {
  try {
    if (detail.recordId) {
      const response = await store.dispatch('meals/updateMealRecord', {
        recordId: detail.recordId,
        data: {
          mealType: detail.mealType,
          recordTime: detail.recordTime + ':00',
          recordDate: selectedDate.value,
          userId: userId.value,
          details: detail.details.map(d => ({
            detailId: d.detailId,
            foodId: d.foodId,
            quantity: d.quantity,
            food: d.food
          }))
        }
      })
      
      if (response) {
        ElMessage.success('更新成功')
        await fetchDailyRecords()
      }
      return
    }

    const response = await request({
      url: '/api/meal-records',
      method: 'POST',
      data: {
        mealType: detail.mealType,
        recordDate: selectedDate.value,
        userId: userId.value,
        recordTime: detail.recordTime + ':00',
        details: detail.details
      }
    })

    if (response?.success) {
      ElMessage.success('添加成功')
      await fetchDailyRecords()
    } else {
      throw new Error(response?.message || '添加失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

const handleEdit = async (detail) => {
  try {
    const record = mealRecords.value.find(r => 
      r.details.some(d => d.detailId === detail.detailId)
    )
    
    if (!record) {
      throw new Error('未找到对应的记录')
    }

    editingRecord.value = record
    showEditDialog.value = true
  } catch (error) {
    console.error('编辑失败:', error)
    ElMessage.error(error.message || '编辑失败')
  }
}

const handleEditConfirm = async (updatedRecord) => {
  try {
    const response = await store.dispatch('meals/updateMealRecord', {
      recordId: updatedRecord.recordId,
      data: {
        mealType: updatedRecord.mealType,
        recordTime: updatedRecord.recordTime + ':00',
        recordDate: selectedDate.value,
        userId: userId.value,
        details: updatedRecord.details.map(d => ({
          detailId: d.detailId,
          foodId: d.food.foodId,
          quantity: d.quantity,
          food: d.food
        }))
      }
    })
    
    if (response) {
      ElMessage.success('更新成功')
      showEditDialog.value = false
      await fetchDailyRecords()
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error(error.message || '更新失败')
  }
}

const handleDelete = (record) => {
  if (!userId.value) {
    ElMessage.warning('请先登录')
    return
  }

  ElMessageBox.confirm(
    '确定要删除这条膳食记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await store.dispatch('meals/deleteMealRecord', {
        recordId: record.recordId,
        userId: userId.value
      })
      
      ElMessage.success('删除成功')
      await fetchDailyRecords()
    } catch (error) {
      if (error.message !== 'cancel') {
        ElMessage.error(error.message || '删除失败')
      }
    }
  }).catch(() => {})
}

// 计算总营养素
const totalNutrition = computed(() => {
  if (!mealRecords.value?.length) return { calories: 0, protein: 0, carbohydrates: 0, fat: 0 }
  
  return mealRecords.value.reduce((acc, record) => {
    record.details?.forEach(detail => {
      const quantity = detail.quantity || 0
      const food = detail.food || {}
      acc.calories += (food.calories || 0) * quantity
      acc.protein += (food.protein || 0) * quantity
      acc.carbohydrates += (food.carbohydrates || 0) * quantity
      acc.fat += (food.fat || 0) * quantity
    })
    return acc
  }, { calories: 0, protein: 0, carbohydrates: 0, fat: 0 })
})

const showAddFoodDialog = ref(false)
const showEditDialog = ref(false)
const editingRecord = ref(null)
</script>

<style scoped>
.meal-record-page {
  min-height: 100vh;
  background: var(--el-fill-color-extra-light);
  padding: 2rem;
}

.page-container {
  max-width: 800px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.nutrition-summary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.page-title {
  margin: 0;
  color: var(--el-text-color-primary);
  font-weight: 600;
}

.loading-state {
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.empty-state {
  padding: 4rem 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  text-align: center;
}

@media (max-width: 768px) {
  .meal-record-page {
    padding: 1rem;
  }

  .header {
    flex-direction: column;
    gap: 1rem;
  }

  .sub-header {
    flex-direction: column;
    align-items: stretch;
  }

  .empty-state {
    padding: 2rem 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style>